import { ref, nextTick } from 'vue';

/**
 * 单词学习模块
 * 针对听力测试场景优化
 */
export const useWordLearning = (
  lessonId,
  wordData,
  ui,
  speech,
  WORD_STATUS,
  sessionProgress
) => {
  const isLoading = ref(false);

  /**
   * 加载单词数据
   */
  const loadWordData = async () => {
    try {
      isLoading.value = true;
      
      // 模拟API加载数据
      // 实际项目中应替换为真实API调用
      const mockData = {
        words: [
          {
            id: '1',
            content: 'parasite',
            usphone: 'pærəsaɪt',
            definition: 'n. 寄生虫，寄生动植物',
            example: {
              text: 'Many diseases are caused by parasites.',
              translation: '许多疾病都是由寄生虫引起的。',
              highlight: 'parasites'
            },
            relatedWords: [
              { word: 'parasitic', partOfSpeech: 'adj.', definition: '寄生的；由寄生虫引起的' },
              { word: 'parasitize', partOfSpeech: 'v.', definition: '寄生于；侵害；使寄生' }
            ],
            wordFamily: '派生'
          },
          {
            id: '2',
            content: 'abundant',
            usphone: 'əˈbʌndənt',
            definition: 'adj. 丰富的；充裕的；大量的',
            example: {
              text: 'The region has abundant natural resources.',
              translation: '该地区拥有丰富的自然资源。',
              highlight: 'abundant'
            },
            relatedWords: [
              { word: 'abundance', partOfSpeech: 'n.', definition: '丰富，充裕；大量' },
              { word: 'abundantly', partOfSpeech: 'adv.', definition: '丰富地；大量地' }
            ],
            wordFamily: '派生'
          },
          {
            id: '3',
            content: 'crucial',
            usphone: 'ˈkruːʃl',
            definition: 'adj. 关键的；决定性的；至关重要的',
            example: {
              text: 'Getting enough sleep is crucial for good health.',
              translation: '获得充足的睡眠对健康至关重要。',
              highlight: 'crucial'
            },
            relatedWords: [
              { word: 'crucially', partOfSpeech: 'adv.', definition: '至关重要地；决定性地' }
            ],
            wordFamily: '派生'
          },
          {
            id: '4',
            content: 'deteriorate',
            usphone: 'dɪˈtɪriəreɪt',
            definition: 'v. 恶化；变质；退化',
            example: {
              text: 'The patient\'s condition continued to deteriorate.',
              translation: '患者的状况持续恶化。',
              highlight: 'deteriorate'
            },
            relatedWords: [
              { word: 'deterioration', partOfSpeech: 'n.', definition: '恶化；退化；变质' }
            ],
            wordFamily: '派生'
          },
          {
            id: '5',
            content: 'eloquent',
            usphone: 'ˈeləkwənt',
            definition: 'adj. 雄辩的；有口才的；动人的',
            example: {
              text: 'She gave an eloquent speech about climate change.',
              translation: '她就气候变化发表了一篇雄辩的演讲。',
              highlight: 'eloquent'
            },
            relatedWords: [
              { word: 'eloquence', partOfSpeech: 'n.', definition: '雄辩；口才；修辞' },
              { word: 'eloquently', partOfSpeech: 'adv.', definition: '雄辩地；有口才地' }
            ],
            wordFamily: '派生'
          }
        ]
      };
      
      // 设置学习队列
      wordData.learningQueue = mockData.words;
      wordData.knownQueue = [];
      
      // 设置学习状态
      wordData.learningState = {
        totalWords: mockData.words.length,
        learnedWords: 0,
        currentWordIndex: 0,
        totalVocabularyProgress: {
          totalLearnedWords: 0,
          totalWords: mockData.words.length
        }
      };
      
      // 设置当前单词
      setCurrentWord();
      
    } catch (error) {
      console.error('加载单词数据失败:', error);
    } finally {
      isLoading.value = false;
    }
  };
  
  /**
   * 设置当前单词
   */
  const setCurrentWord = () => {
    if (wordData.learningQueue.length > 0) {
      wordData.currentWord = wordData.learningQueue[0];
      
      // 听力测试中，自动播放单词发音
      nextTick(() => {
        // 重复播放单词发音，增强听力训练效果
        speech.repeatPronunciation(2, 1500);
      });
    } else {
      wordData.currentWord = null;
    }
    
    // 重置界面状态
    ui.showDefinition = false;
    ui.showAllRelatedWords = false;
  };
  
  /**
   * 处理用户对单词的响应
   * @param {string} responseType - 'know', 'fuzzy', 或 'unknown'
   */
  const handleResponse = (responseType) => {
    if (!wordData.currentWord) return;
    
    // 显示单词释义
    ui.showDefinition = true;
    
    // 根据用户反馈调整单词位置
    const currentWord = wordData.currentWord;
    
    if (responseType === 'know') {
      // 认识：移到已知队列
      wordData.knownQueue.push(currentWord);
      wordData.learningQueue.shift();
      sessionProgress.learned++;
      sessionProgress.needsSaving = true;
    } else if (responseType === 'fuzzy') {
      // 模糊：移到队列中间位置
      wordData.learningQueue.shift();
      const insertPosition = Math.min(6, wordData.learningQueue.length);
      wordData.learningQueue.splice(insertPosition, 0, currentWord);
    } else if (responseType === 'unknown') {
      // 不认识：移到队列前方位置
      wordData.learningQueue.shift();
      const insertPosition = Math.min(3, wordData.learningQueue.length);
      wordData.learningQueue.splice(insertPosition, 0, currentWord);
    }
    
    // 播放单词发音，帮助用户记忆
    speech.playPronunciation();
  };
  
  /**
   * 处理下一个单词
   */
  const handleNextWord = () => {
    setCurrentWord();
  };
  
  /**
   * 处理用户点击"记错了"
   */
  const handleWrong = () => {
    if (!wordData.currentWord) return;
    
    // 如果用户点击"记错了"，将单词从已知队列移回到学习队列前方
    if (wordData.knownQueue.length > 0) {
      const lastKnownWord = wordData.knownQueue.pop();
      wordData.learningQueue.unshift(lastKnownWord);
      sessionProgress.learned--;
      sessionProgress.needsSaving = true;
    }
    
    setCurrentWord();
  };
  
  /**
   * 保存学习进度
   */
  const saveProgress = async () => {
    if (!sessionProgress.needsSaving) return;
    
    try {
      // 实际项目中应替换为真实API调用
      console.log('保存进度:', {
        lessonId,
        learnedCount: sessionProgress.learned,
        totalWords: wordData.learningState.totalWords
      });
      
      sessionProgress.needsSaving = false;
      return true;
    } catch (error) {
      console.error('保存进度失败:', error);
      return false;
    }
  };

  return {
    loadWordData,
    handleResponse,
    handleNextWord,
    handleWrong,
    saveProgress,
    isLoading
  };
}; 